package com.hc.serviceimpl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.bean.SysRole;
import com.hc.bean.UserRoleResultModel;
import com.hc.entity.SysUserInfo;
import com.hc.mapper.SysUserInfoMapper;
import com.hc.service.SysUserInfoService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hc
 */
@Service
public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUserInfo> implements SysUserInfoService {

    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;

    @Override
    public UserRoleResultModel userLogin(UserRoleResultModel userRoleResultModel) {
        String account = userRoleResultModel.getAccount();
        if(StringUtils.isBlank(account)){
            throw  new RuntimeException("账号不能为空");
        }
        String password = userRoleResultModel.getPassword();
        if(StringUtils.isBlank(password)){
            throw new RuntimeException("密码不能为空");
        }
        SysUserInfo one = getOne(Wrappers.lambdaQuery(new SysUserInfo()).eq(SysUserInfo::getAccount, account).eq(SysUserInfo::getPassword, password));
        if(ObjectUtils.isEmpty(one)){
            throw new RuntimeException("账号或密码错误");
        }
        UserRoleResultModel user = new UserRoleResultModel();
        String userId = one.getUserId();
        BeanUtils.copyProperties(one,user);
        List<SysRole> userRole = sysUserInfoMapper.getUserRole(userId);
        user.setRoleList(userRole);
        user.setUserId(Integer.parseInt(userId));
        return user;
    }

    @Override
    public List<SysUserInfo> getLabUsers(String roleId) {
        List<SysUserInfo> labUsers = sysUserInfoMapper.selectList(Wrappers.emptyWrapper());
        List<SysRole> sysRoles = sysUserInfoMapper.getAllRoles();
        Map<String, List<SysRole>> collect = sysRoles.stream().collect(Collectors.groupingBy(SysRole::getUserId));
        for (SysUserInfo userRoleResultModel : labUsers) {
            String userId = userRoleResultModel.getUserId();
            if (StringUtils.isNotEmpty(userId)){
                List<SysRole> sysRoles1 = collect.get(userId);
                if (CollectionUtils.isNotEmpty(sysRoles1)){
                    userRoleResultModel.setRoleList(sysRoles1);
                }
            }
        }
        return  labUsers;
    }

    @Override
    public UserRoleResultModel otherSystemLongin(UserRoleResultModel userRoleResultModel) {
        return userLogin(userRoleResultModel);
    }

}
